package top.heue.utils.container

import android.view.KeyEvent
import android.view.View
import androidx.fragment.app.Fragment
import top.heue.utils.base.R
import top.heue.utils.base.base.BaseActivity
import top.heue.utils.base.base.BaseFragment
import top.heue.utils.base.databinding.ActivityContainBinding
import top.heue.utils.base.helper.inflate
import top.heue.utils.container.FragmentContainer.TAG_ID
import top.heue.utils.log.L

open class ContainActivity : BaseActivity() {
    private var containConfig: ContainConfig? = null
    private var containCallback: ContainCallback? = null
    private var fragment: Fragment? = null
    protected val bind: ActivityContainBinding by inflate {
        config = containConfig
    }

    override fun onCreate() {
        super.onCreate()
        containConfig = FragmentContainer.config(intent.extras?.getInt(TAG_ID))
        containCallback = containConfig?.getCallback(this)
        containCallback?.onLoaded()
        setContentView(bind.root)
        viewInit()
    }


    private fun viewInit() {
        supportFragmentManager.fragments.forEach {
            fragment = it
        }
        if (containConfig != null) {
            fragment = fragment?: containConfig!!.getFragment()
            val transaction = supportFragmentManager.beginTransaction()
            if (!fragment!!.isAdded)
                transaction.add(R.id.layout_container, fragment!!, containConfig!!.tag)
                    //.setReorderingAllowed(true)
                    //.addToBackStack(null)
            else transaction.show(fragment!!)
            transaction.commit()
            bind.txtTip.visibility = View.GONE
            containCallback?.onSucceed()
        } else {
            //为了解决重启应用不明原因的是ContainActivity，在这里加入了判断是否是通过FragmentContainer打开
            L.e("传入id为空，无法显示页面")
            bind.txtTip.visibility = View.VISIBLE
            containCallback?.onFailed()
        }
    }

    /**
     * OnKeyDown Event For Fragment
     */
    override fun onKeyDown(keyCode: Int, event: KeyEvent?): Boolean {
        if (fragment != null && fragment is BaseFragment) {
            val bool = (fragment as BaseFragment).onKeyDown(keyCode, event)
            if (!bool) return true
        }
        return super.onKeyDown(keyCode, event)
    }

    override fun onDestroy() {
        super.onDestroy()
        FragmentContainer.destroy(containConfig!!.id)
    }
}